package com.weiming.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${order.test}")
    private String configName;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     * 使用LoadBalanceClient进行选择负载均衡
     * @return
     */
    @RequestMapping("order")
    public String orderProduct(){
        System.out.println(configName);
        ServiceInstance serviceInstance = loadBalancerClient.choose("storage-client");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/reduce";
        System.out.println(url);

        return restTemplate.getForObject(url, String.class);
        // return restTemplate.getForObject("http://storage-client/reduce", String.class);
    }

    /**
     * 集成Feign之后，本身Feign已经集成了负载均衡，所有不用单独写负载均衡
     *
     * @return
     */
    @RequestMapping("feignOrder")
    public String feignReduceStorage(){
        return orderFeignClient.reduce();
    }
}
